<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>greeting</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.6.1/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <style>
        #mainWrapper {
            width: 600px;
            margin: auto;
        }
    </style>
</head>
<body>
<div id="mainWrapper">
    <div id="msgWrapper">
        <p style="vertical-align: top">Token：</p>
        <textarea id="token" style="width: 400px;height: 30px">02e125ed-79c4-414c-87b3-b65f1897549a</textarea>
        <p style="vertical-align: top">服务地址：</p>
        <textarea id="url" style="width: 400px;height: 30px">/vibase-api/websocket</textarea>

        <p style="vertical-align: top">订阅主题：</p>
        <textarea id="subscribe" style="width: 400px;height: 30px">/topic/device</textarea>

        <p style="vertical-align: top">发送的消息:</p>
        <textarea id="msgSentTopic" style="width: 400px;height: 30px">/topic/device</textarea>
        <textarea id="msgSent" style="width: 400px;height: 100px"></textarea>
        <p style="vertical-align: top">收到的消息:</p>
        <textarea id="msgReceived" style="width: 400px;height: 100px"></textarea>
    </div>
    <div style="margin-top: 5px;">
        <button onclick="connect()">连接</button>
        <button onclick="subscribe()">订阅主题</button>
        <button onclick="sendMessage()">发送消息</button>
        <button onclick="disconnect()">断开连接</button>
    </div>
</div>
<script type="text/javascript">
    $(() => {
        $('#msgSent').val('');
        $("#msgReceived").val('');
    });

    let stompClient = null;

    // 连接服务器
    const connect = () => {
        var url = $("#url").val();
        const ws = new SockJS(url);
        stompClient = Stomp.over(ws);

        var token = $("#token").val();

        var header = {
            'x-header-token': token,
            'x-header-platform': 'web'
        }

        stompClient.connect(header, () => {
            print('Connected to websocket server!');
        });
    }

    const subscribe = () => {
        stompClient.subscribe($('#subscribe').val(), function (message) {
                console.log(`Received message: ${message.body}`);
                print(message.body);
            }
        );
    }

    // 断连
    const disconnect = () => {
        stompClient.disconnect(() => {
            print('Disconnected from WebSocket server');
        });
    }

    // 发送消息，这里直接发的是文本
    const sendMessage = () => {
        var topic = $('#msgSentTopic').val();
        stompClient.send(topic, {}, $('#msgSent').val());
    }

    const print = (msg) => {
        $("#msgReceived").val(msg);
    }
</script>
</body>
</html>
